<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center">
                        <div v-if="!route.query.id">新增退货单</div>
                        <div v-else>
                            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
                                退货单编码:
                            </span>
                            <el-tag>{{ route.query.code }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div class="flex items-center" v-if="Boolean(!route.query.readonly)">
                        <el-button type="primary" @click="submitForm">保 存</el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form :model="form" :rules="rules" :disabled="Boolean(route.query.readonly)"
                            ref="materialReceiptRef" label-width="100px">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="供应商" prop="supplierName">
                                        <el-input v-model="form.supplierName" placeholder="请选择供应商"
                                            @click="() => { supplierVisible = true }" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="制单人" prop="createBy">
                                        <el-input v-model="form.createBy" placeholder="自动带出" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="退货日期" prop="rejectDate">
                                        <el-date-picker style="width: 100%" v-model="form.rejectDate" type="datetime"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="创建时间" prop="createTime">
                                        <el-date-picker style="width: 100%" v-model="form.createTime" type="datetime"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
                <el-collapse-item disabled  title="退库明细" name="2">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">退货明细</span>
                    </template>
                    <el-button style="margin-bottom: 10px;" type="primary" size="small" @click="handleMateriel"
                        :disabled="Boolean(route.query.readonly)">从物料库选择</el-button>
                    <el-table v-loading="loading" class="table-form" :data="mesMaterialRejectdetailList"
                        :header-cell-class-name="must">
                        <el-table-column label="序号" width="60" type="index" align="center" :header-cell-class-name="must">
                        </el-table-column>
                        <!--<el-table-column label="入库单编码" min-width="120" align="center" prop="inCode"
                            :show-overflow-tooltip="true" />-->
                        <el-table-column label="物料分类" min-width="150" align="center" prop="className"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="物料编码" min-width="150" align="center" prop="materialCode"
                            :show-overflow-tooltip="true">

                        </el-table-column>
                        <el-table-column label="物料名称" min-width="150" align="center" prop="materialName"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="规格型号" min-width="120" align="center" prop="specs"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="单位" min-width="120" align="center" prop="unit"
                            :show-overflow-tooltip="true">
                            <template #default="scope">
                                <dict-tag :options="mes_material_unit" :value="scope.row.unit" />
                            </template>
                        </el-table-column>
<!--                        <el-table-column label="库存数量" prop="stockNum" align="center" width="130">-->
<!--                        </el-table-column>-->
                        <el-table-column label="退货数量" prop="quantity" align="center" width="130">
                            <template #default="scope">
                                <el-input v-model="scope.row.quantity" :disabled="Boolean(route.query.readonly)"
                                    @change="SumAmount(scope.row)" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="price" disabled align="center" width="120">
                        </el-table-column>
                        <el-table-column label="金额" prop="amount" disabled align="center" width="120">
                        </el-table-column>
                        <el-table-column label="备注" prop="remark" align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.remark" :disabled="Boolean(route.query.readonly)"
                                    placeholder="请输入备注" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-tooltip content="删除" placement="top">
                                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                        :disabled="Boolean(route.query.readonly)"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <!-- 选择供应商 -->
        <SearchSupplier :visible="supplierVisible" @changeUpdate="changeSupplierData"
            @cancel="() => { supplierVisible = false }"></SearchSupplier>
        <!-- 从入库单选择 -->
        <searchMaterialReceipt :visible="searchMaterialReceiptVisible" @changeUpdate="changeSearchMaterialReceipt"
            :receiptList="receiptList"  @cancel="() => { searchMaterialReceiptVisible = false }"></searchMaterialReceipt>
    </div>
</template>
<script setup>
import { getMaterialreject,addMaterialreject, updateMaterialreject  } from '@/api/storage/returnNote.js'

import SearchSupplier from '@/components/SearchSupplier'
import searchMaterialReceipt from './searchMaterialReceipt.vue'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance();
const { mes_material_unit } = proxy.useDict('mes_material_unit');
const route = useRoute()
const router = useRouter()
const activeNames = ['1', '2']
const materialReceiptRef = ref(null)
const searchMaterialReceiptVisible = ref(false)
const loading = ref(false)
const userInfo = useUserStore()
const mesMaterialRejectdetailList = ref([])
const supplierVisible = ref(false)
const receiptList = ref([])

const data = reactive({
    form: {
    },
    rules: {
        supplierName: [{ required: true, message: "供应商不能为空", trigger: "change" },],
        rejectDate: [{ required: true, message: "退货日期不能为空", trigger: ["blur", "change"] }],
        createBy: [{ required: true, message: "创建人不能为空", trigger: ["change"] }],
        createTime: [{ required: true, message: "创建时间不能为空", trigger: ["change"] }],
    }
});
const { form, rules } = toRefs(data);
if (route.query.id) {
    getMaterialreject(route.query.id).then(response => {
        form.value = response.data
        //mesMaterialRejectdetailList.value = response.data.mesMaterialRejectdetailList
        response.data.mesMaterialRejectdetailList.forEach(ele => {
            ele.id = ele.materialId;
            mesMaterialRejectdetailList.value.push(ele);
        });
    })

} else {
    form.value = {}
    form.value.createBy = userInfo.name

}
// 获取当前时间
const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    form.value.rejectDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
getCurrentDateTime()

// 选中供应商
const changeSupplierData = (row) => {
    console.log('row', row)
    form.value.supplierCode = row.supplierCode
    form.value.supplierName = row.name
    supplierVisible.value = false
}

//20240314 修改 选择页面添加了复选框，选择之后不能自动带出
// const changeSearchMaterialReceipt = (row) => {
//     debugger
//     console.log('row', row)
//     const rowInfo = { ...row }
//     delete rowInfo.quantity
//     delete rowInfo.amount
//     delete rowInfo.remark
//     rowInfo.materialindetailId = row.id
//     // rowInfo.materialId = row.materialId
//     // rowInfo.materialusedetailId = row.id
//     mesMaterialRejectdetailList.value.push(rowInfo)
//     searchMaterialReceiptVisible.value = false
// }
const changeSearchMaterialReceipt = (row) => {
    console.log('row', row);
    //清空之前的选择
    mesMaterialRejectdetailList.value = []
    row.forEach(ele => {
        delete ele.quantity;
        delete ele.amount;
        ele.authorityPrice = ele.price;
        ele.quantity = ele.total ; //退货数量默认为库存数，可以编辑
        ele.stockNum = ele.total;
        ele.materialindetailId = ele.id;
        ele.materialId = ele.id;
        mesMaterialRejectdetailList.value.push(ele);
        SumAmount(ele)
    });
    mesMaterialRejectdetailList.value = uniqueByMaterialId(mesMaterialRejectdetailList.value)
    searchMaterialReceiptVisible.value = false;
}
const uniqueByMaterialId = (list) => {
    const seenMaterialIds = {};
    return list.reduce((acc, curr) => {
        if (!seenMaterialIds[curr.id]) {
            seenMaterialIds[curr.id] = true;
            acc.push(curr);
        }
        return acc;
    }, []);
};

//选择入库单 修改成从物料库选择
const handleMateriel = () => {
    receiptList.value = mesMaterialRejectdetailList.value
    searchMaterialReceiptVisible.value = true
}
const SumAmount = (row) => {
    if (Number(row.quantity) > row.stockNum) {
        row.quantity = null
        ElMessage({
            message: '数量不能大于库存数量',
            type: 'warning',
        })
        return
    }
    //选择之后由于数量没有填写会显示NaN 这个地方修改成0
    //row.amount = Number((Number(row.quantity) * Number(row.price)).toFixed(4))
    row.amount=row.quantity==undefined?0:Number((Number(row.quantity) * Number(row.price)).toFixed(4));
    console.log('amount:', row.amount);
}
// 删除
const handleDelete = (row) => {
    proxy.$modal.confirm('是否确认删除该数据？').then(function () {
        mesMaterialRejectdetailList.value = mesMaterialRejectdetailList.value.filter(item => item.id !== row.id)
        proxy.$modal.msgSuccess("删除成功");
    })
}
// 确认
const submitForm = () => {
    const screen = mesMaterialRejectdetailList.value.find(item => {
        return !item.quantity && item.quantity != 0
    })
    if (screen) {
        ElMessage({
            message: '请填写退货明细中的退货数量字段',
            type: 'warning',
        })
        return
    }
    materialReceiptRef.value.validate(valid => {
        if (valid) {
            if (route.query.id) {
                updateMaterialreject({ ...form.value, mesMaterialRejectdetailList: mesMaterialRejectdetailList.value }).then(res => {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    goBack()
                })
            } else {
                addMaterialreject({ ...form.value, status: 0, mesMaterialRejectdetailList: mesMaterialRejectdetailList.value }).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    goBack()
                })
            }
        }
    });
}

const must = (obj) => {
    let mustColumns = []
    mustColumns = [8];
    if (mustColumns.includes(obj.columnIndex)) {
        return 'must';
    }
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    //router.go(-1)
    if(route.query.moduleCode=="searchReturnNote"){
        router.push('/material/searchReturnNote')
    }else{
        router.push('/material/returnNote')
    }
    // router.push('/storage/returnNote')
}

</script>

<style lang="scss" scoped>
.footer {
    text-align: center;
}

:deep(.el-pagination) {
    position: unset;
}

.table-form :deep(.el-form-item) {
    margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
    content: '*';
    color: #ff1818;
}
</style>